import React, { Suspense, useState, useRef, useEffect } from 'react'

interface Props {
  loadingDelay: number;
}

const AsyncComponent: React.FC<Props> = ({ children, loadingDelay = 0 }) => {
  const [loading, setLoading] = useState(false)
  const delay = useRef(0)

  useEffect(() => {
    delay.current = setTimeout(() => setLoading(true), loadingDelay)
    return (): void => {
      clearTimeout(delay.current)
    }
  }, [loadingDelay])

  return (
    <Suspense fallback={loading && <div>async component loading...</div>}>
      {children}
    </Suspense>
  )
}

export function importer (path: string): React.LazyExoticComponent<any> {
  return React.lazy(() =>
    import(
      /* webpackChunkName: "chunk-[request][index]" */
      `@/containers${path}`
    )
  )
}

export default AsyncComponent
